package com.online.customerchatserver.service;

import com.alibaba.fastjson.JSON;
import com.online.customerchatserver.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 *   redis缓存
 *   @author hsc
 *   @create 2018-04-28 10:35
 */
@Service
public class RedisService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public String getStr(String key) {
        String source = (String) stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return source;
        }
        return null;
    }

    public boolean delete(String key) {
        return stringRedisTemplate.delete(key);
    }

    public void add(String sessionId, Message message) {
        String source = JSON.toJSONString(message);
        stringRedisTemplate.opsForList().leftPush(sessionId, source);
    }

    public void add(String eId, String customerId, List<String> ids) {
        String source = JSON.toJSONString(ids);
        stringRedisTemplate.opsForHash().put(eId, customerId, source);
       // stringRedisTemplate.expire(eId, time, TimeUnit.DAYS);
    }

    public void add(String eId, String customerId, String id) {
        stringRedisTemplate.opsForHash().put(eId, customerId, id);
       // stringRedisTemplate.expire(eId, time, TimeUnit.DAYS);
    }

    public String getId(String key, String hashKey) {
        String source  = (String) stringRedisTemplate.opsForHash().get(key, hashKey);
        if (!StringUtils.isEmpty(source)) {
            return JSON.toJSONString(source);
        }
        return null;
    }

    public String getIds(String key, String hashKey) {
        String source = (String) stringRedisTemplate.opsForHash().get(key, hashKey);
        if (!StringUtils.isEmpty(source)) {
            return JSON.toJSONString(source);
        }
        return null;
    }


    public List<Message> getMessageList(String key) {
        String source = (String) stringRedisTemplate.opsForList().leftPop(key);
        if (!StringUtils.isEmpty(source)) {
            return JSON.parseArray(source,Message.class);
        }
        return null;
    }

    public  boolean hasKeyForValue(String key,  String value) {
        return  stringRedisTemplate.opsForValue().setIfAbsent(key , value);
    }

    public  boolean hasKeyForHash(String key, String hashKey) {
        return  stringRedisTemplate.opsForHash().hasKey(key, hashKey);
    }

//    public void delete(String key) {
//        stringRedisTemplate.opsForValue().getOperations().delete(key);
//    }
}
